package com.spring.controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    //定义list集合,这个集合可以先简单理解为1张表,Map是表中的记录对象
    private List<Map<String,String>> dbList=new ArrayList<>();
    public AjaxController(){
        Map<String,String> map=new HashMap<String,String>();
        map.put("id","100");
        map.put("city","beijing");
        dbList.add(map);
        map=new HashMap<String,String>();
        map.put("id","101");
        map.put("city","shanghai");
        dbList.add(map);
    }
    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "Response Result Of Ajax Get Request 01 ";
    }

    @GetMapping(path={"/doAjaxGet/{city}","/doAjaxGet"})
    public List<Map<String,String>> doAjaxGet(
            @PathVariable(required=false) String city){
        List<Map<String,String>> list=new ArrayList<>();
        for(Map<String,String> map:dbList){
            if(map.get("city").contains(city)){
                list.add(map);
            }
        }
        return list;
    }

    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,String>  map){
        dbList.add(map);
        System.out.println(dbList);
        return "save ok";
    }

    @PostMapping("/doAjaxPostJson")
    public String doAjaxPostJson(@RequestBody Map<String,String>  map){
        System.out.println("map="+map);
        dbList.add(map);
        System.out.println(dbList);
        return "save ok";
    }

    @DeleteMapping("/doAjaxDelete/{id}")
    public String doDeleteObject(@PathVariable  String id){
        //基于迭代器执行删除操作
        Iterator<Map<String,String>> it=dbList.iterator();
        while(it.hasNext()){
            Map<String,String> map=it.next();
            if(map.get("id").equals(id)){
                it.remove();//基于迭代器执行删除操作
            }
        }
        System.out.println(dbList);
        return "delete ok";
    }

    @PutMapping("/doAjaxPut")
    public String doAjaxPut(@RequestParam Map<String,String> paramMap){
        for(Map<String,String> map:dbList){
            if(map.get("id").equals(paramMap.get("id"))){
                map.put("city",paramMap.get("city"));
            }
        }
        System.out.println(dbList);
        return "update ok";
    }
}